<?php

namespace App\Jobs;

use App\Events\RefreshUserInfo;
use App\Models\Agent;
use App\Models\AgentRevenue;
use App\Models\AgentReward;
use App\Models\AgentRewardRuleSettings;
use App\Models\CommodityActivityStatistics;
use App\Models\DailyReportStatistics;
use App\Models\IndicatorsDailySummary;
use App\Models\Order;
use App\Models\SummaryBase;
use App\Services\CacheLockKeyConst;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Support\Str;

/**
 * 下单后的各种统计数据
 * Class AgentsAccumulateAfterPlacingOrdersJob
 * @package App\Jobs
 */
class AgentsAccumulateAfterPlacingOrdersJob extends Job
{
    private $orderId;

    /** @var Order */
    private $order;

    /** @var CarbonInterface */
    private $orderCreatedAt;

    /** @var Agent */
    private $agent;

    private $agentSnapshot;

    /** @var Agent */
    private $directInviter;

    private $directInviterSnapshot;

    /** @var Agent */
    private $indirectInviter;

    private $indirectInviterSnapshot;

    /**
     * sku 统计的 model
     * @var array
     */
    private $commodityActivitySkuStatistics = [];

    /**
     * 重试就一次
     * @var int
     */
    public $tries = 1;

    public function __construct($orderId)
    {
        $this->orderId = $orderId;
    }

    public function handle()
    {
        try {
            // 这里的 order id 有可能不存在
            $this->order = Order::query()->with(['agent', 'skus', 'directInviter', 'indirectInviter'])->findOrFail($this->orderId);
            $this->orderCreatedAt = Carbon::parse($this->order['created_at']);
            $this->agent = $this->order->agent;
            $this->agentSnapshot = $this->order->agent_snapshot;
            $this->directInviter = $this->order->directInviter;
            $this->directInviterSnapshot = $this->order->direct_inviter_snapshot;
            $this->indirectInviter = $this->order->indirectInviter;
            $this->indirectInviterSnapshot = $this->order->indirect_inviter_snapshot;

            // 解决 firstOrCreate 并发问题, 先创建
            // [统计] 每日报表
            /** @var DailyReportStatistics $dailyReportStatistics */
            $dailyReportStatistics = CacheLockKeyConst::dailyReportStatistics($this->orderCreatedAt);
            // [统计] 活动 SKU
            $this->order->skus->each(fn($orderSku) => $this->commodityActivitySkuStatistics[$orderSku['id']] = CacheLockKeyConst::commodityActivitySkuStatistics(
                $orderSku['commodity_activity_sku_id'], $this->order['commodity_id'], $this->order['commodity_activity_id']));
            // [统计] 活动
            /** @var CommodityActivityStatistics $commodityActivityStatistics */
            $commodityActivityStatistics = CacheLockKeyConst::commodityActivityStatistics($this->order['commodity_id'], $this->order['commodity_activity_id']);

            // 当前代理商业绩累加
            $orderAmount = $this->order['total_amount']; // 订单总额
            $this->agentIncomeAccumulate($orderAmount);

            // 每日下单奖励
            $this->whetherToReachTheDailyReward();
            // 每月下单奖励
            $this->whetherToReachTheMonthlyReward();

            $directInviterReward = []; // 直接邀请奖励
            $indirectInviterReward = []; // 间接邀请奖励
            $levelGradeDifference = []; // 层级差价
            $calculationLevelGradeDifferenceFun = function ($orderSku, $skuSnapShot, $superior, $subordinate, &$levelGradeDifference) {
                // 这一方法是计算佣金
                $unitPrice = abs($skuSnapShot[$subordinate . '_price'] - $skuSnapShot[$superior . '_price']); // 层级差价 (单价) ['strongman']['elite'] 大咖 => 精英 的差价
                $singleTotalPrice = $unitPrice * $orderSku['amount']; // 单次 sku 总额
                $levelGradeDifference[$superior][$subordinate]['total'] = ($levelGradeDifference[$superior][$subordinate]['total'] ?? 0) + $singleTotalPrice; // 差价 * sku 数量 = 层级差价所有 sku 加起来的总额
                $levelGradeDifference[$superior][$subordinate]['sku_details'][$orderSku['id']] = [
                    'quantity' => $orderSku['amount'], // sku_id 对应 order sku 数量
                    'total' => $singleTotalPrice, // sku_id 对应 总额
                    'unit_price' => $unitPrice,
                ];
            };
            foreach ($this->order->skus as $orderSku) {
                $skuSnapShot = $orderSku['sku_snapshot']; // commodity_activity_sku 快照
                // 注意这里的结构和 $calculationLevelGradeDifferenceFun 方法内 $levelGradeDifference 的结构一致, 在 invitationReward 方法内用到
                $directInviterSingleSkuTotalReward = $orderSku['amount'] * $skuSnapShot['direct_invitation'];
                $directInviterReward['total'] = ($directInviterReward['total'] ?? 0) + $directInviterSingleSkuTotalReward; // 直接邀请 所有 sku 奖励总和
                $directInviterReward['sku_details'][$orderSku['id']] = ['quantity' => $orderSku['amount'], 'total' => $directInviterSingleSkuTotalReward, 'unit_price' => $skuSnapShot['direct_invitation'],]; // 直接邀请 单独 sku 奖励和

                $indirectInviterSingleSkuTotalReward = $orderSku['amount'] * $skuSnapShot['indirect_invitation'];
                $indirectInviterReward['total'] = ($indirectInviterReward['total'] ?? 0) + $indirectInviterSingleSkuTotalReward; // 间接邀请 所有 sku 奖励总和
                $indirectInviterReward['sku_details'][$orderSku['id']] = ['quantity' => $orderSku['amount'], 'total' => $indirectInviterSingleSkuTotalReward, 'unit_price' => $skuSnapShot['indirect_invitation']]; // 间接邀请 单独 sku 奖励和

                // 层级差价计算
                $calculationLevelGradeDifferenceFun($orderSku, $skuSnapShot, 'strongman', 'elite', $levelGradeDifference);
                $calculationLevelGradeDifferenceFun($orderSku, $skuSnapShot, 'strongman', 'group_owner', $levelGradeDifference);
                $calculationLevelGradeDifferenceFun($orderSku, $skuSnapShot, 'elite', 'group_owner', $levelGradeDifference);

                // [统计] 商品 sku 维度相关数据
                $this->commodityActivitySkuStatistics[$orderSku['id']]->incrementOrDecrementQuantitySold($skuSnapShot['purchase_price'], $orderSku['amount']); // + 销量 和 销量 * 成本单价
                $this->commodityActivitySkuStatistics[$orderSku['id']]->{'incrementOrDecrement' . Str::studly(Agent::LEVEL_MAP[$this->agentSnapshot['level']]['id']) . 'Shipments'}($orderSku['unit_price'], $skuSnapShot['purchase_price'], $orderSku['amount']); // + 当前代理商级别出货量, 数量*等级金额, 数量*成本单价
            }

            // 直接邀请 和 间接邀请
            $this->invitationReward($directInviterReward, $indirectInviterReward, $levelGradeDifference, $orderAmount, $commodityActivityStatistics);

            // 合伙人订单关联
            $this->agent->affiliatedPartner && $this->agent->affiliatedPartner->relatedOrders()->attach([$this->order['id'] => ['type' => Agent::AGENT_ORDER_IDENTITY_PARTNER]]);

            // 晋升 (按照现在代理商的数据来算)
            if (in_array((int) $this->agent->level, [Agent::LEVEL_GROUP_OWNER, Agent::LEVEL_ELITE], true)) {
                $employment = Agent::LEVEL_MAP[$this->agent->level]['employment'];

                $personalPerformance = $this->agent->monthlySummary()
                    ->where('month', $this->orderCreatedAt->format('Ym'))
                    ->where('type', IndicatorsDailySummary::TYPE_AGENT)
                    ->pluck('performance_summary')
                    ->first(null, 0); // 当月个人业绩总和
                $teaPerformance = $this->agent->monthlySummary()
                    ->where('month', $this->orderCreatedAt->format('Ym'))
                    ->where('type', IndicatorsDailySummary::TYPE_TEAM)
                    ->pluck('performance_summary')
                    ->first(null, 0); // 当月团队业绩总和
                if ($personalPerformance >= $employment['self'] && ($personalPerformance + $teaPerformance) >= $employment['team']) {
                    // 三天后校验晋升
                    $this->agent->applyForPromotion();
                }
            }

            // 每日报表统计 订单总数 订单总金额
            $dailyReportStatistics->incrementOrDecrementOrderRelated($orderAmount);

            // 更新订单统计状态为 已完成
            $this->order->update(['settlement_status' => Order::SETTLEMENT_STATUS_COMPLETED]);

        } catch (\Exception $e) {
            \Log::error(sprintf('[统计] 下单 JOB 出错: %s (%s[%d])', $e->getMessage(), $e->getFile(), $e->getLine()));
            throw $e;
        }

        // 通知客户端刷新信息
        event(new RefreshUserInfo($this->agent->getKey()));
    }

    /**
     * 当前代理商业绩累加
     * @param $orderAmount
     */
    private function agentIncomeAccumulate($orderAmount, $method = 'increment'): void
    {
        // 累计收入
        $this->agent->incrementOrDecrementIncome($this->order['income'], $method, $this->orderCreatedAt);
        // 自己业绩
        $this->agent->incrementOrDecrementPerformanceByOrder($orderAmount, $method, $this->orderCreatedAt);
    }

    /**
     * 每日下单奖励
     */
    private function whetherToReachTheDailyReward(): void
    {
        $orderCreatedAtDay = $this->orderCreatedAt->format('Y-m-d'); // 下单日
        $dailySummary = $this->agent->dailySummary()->where(['day' => $orderCreatedAtDay, 'type' => SummaryBase::TYPE_AGENT])->first(); // 当日业绩统计

        // 达到奖励门槛的设置
        $dailyReachTheRewardThreshold = array_filter(
            $this->order['reward_setting_snapshot'],
            fn($setting) => $setting['type'] === AgentRewardRuleSettings::TYPE_DAILY_ORDER_REWARD
                && (($dailySummary['performance_summary'] ?? 0) > $setting['threshold_amount'])
        );
        if (!empty($dailyReachTheRewardThreshold)) {
            // 当日拿到过的奖励
            $theRewardGotToday = $this->agent
                ->rewards()
                ->where('type', AgentRewardRuleSettings::TYPE_DAILY_ORDER_REWARD)
                ->where('award_date', $orderCreatedAtDay)
                ->effective() // 有效的
                ->get()
                ->toArray();
            $theRewardGotToday = arrayCombineByKey($theRewardGotToday, 'reward_setting_id');
            // 到达门槛但是没有获奖记录
            $dailyAgentRewardCreateArr = [];
            foreach ($dailyReachTheRewardThreshold as $rewardSetting) {
                if (!isset($theRewardGotToday[$rewardSetting['id']])) {
                    $dailyAgentRewardCreateArr[] = [
                        'agent_id' => $this->order['agent_id'],
                        'reward_setting_id' => $rewardSetting['id'],
                        'reward_setting_snapshot' => $rewardSetting,
                        'type' => AgentReward::TYPE_DAILY_ORDER_REWARD,
                        'threshold_amount' => $rewardSetting['threshold_amount'],
                        'reward' => $rewardSetting['reward'],
                        'award_date' => $orderCreatedAtDay,
                    ];
                }
            }
            $this->order->agentReward()->createMany($dailyAgentRewardCreateArr);
        }
    }

    /**
     * 每月下单奖励
     */
    private function whetherToReachTheMonthlyReward(): void
    {
        $monthlySummary = $this->agent
            ->monthlySummary()
            ->where(['type' => SummaryBase::TYPE_AGENT, 'month' => (int) $this->orderCreatedAt->format('Ym')])
            ->first(); // 当月业绩统计
        // 达到奖励门槛的设置
        $monthlyReachTheRewardThreshold = array_filter(
            $this->order['reward_setting_snapshot'],
            fn($setting) => $setting['type'] === AgentRewardRuleSettings::TYPE_MONTHLY_ORDER_REWARD
                && (($monthlySummary['performance_summary'] ?? 0) > $setting['threshold_amount'])
        );
        if (!empty($monthlyReachTheRewardThreshold)) {
            // 当月拿到过的奖励
            $theRewardGotThisMonth = $this->agent
                ->rewards()
                ->where('type', AgentRewardRuleSettings::TYPE_MONTHLY_ORDER_REWARD)
                ->whereBetween('award_date', [
                    (clone $this->orderCreatedAt)->startOfMonth()->format('Y-m-d'),
                    (clone $this->orderCreatedAt)->endOfMonth()->format('Y-m-d')
                ])
                ->effective() // 有效的
                ->get()
                ->toArray();
            $theRewardGotThisMonth = arrayCombineByKey($theRewardGotThisMonth, 'reward_setting_id');
            // 到达门槛但是没有获奖记录
            $monthlyAgentRewardCreateArr = [];
            foreach ($monthlyReachTheRewardThreshold as $rewardSetting) {
                if (!isset($theRewardGotThisMonth[$rewardSetting['id']])) {
                    $monthlyAgentRewardCreateArr[] = [
                        'agent_id' => $this->order['agent_id'],
                        'reward_setting_id' => $rewardSetting['id'],
                        'reward_setting_snapshot' => $rewardSetting,
                        'type' => AgentReward::TYPE_MONTHLY_ORDER_REWARD,
                        'threshold_amount' => $rewardSetting['threshold_amount'],
                        'reward' => $rewardSetting['reward'],
                        'award_date' => $this->orderCreatedAt->format('Y-m-d')
                    ];
                }
            }
            $this->order->agentReward()->createMany($monthlyAgentRewardCreateArr);
        }
    }

    /**
     * 直接/间接 邀请奖励
     * @param $directInviterReward
     * @param $indirectInviterReward
     * @param $levelGradeDifference
     * @param $orderAmount
     */
    private function invitationReward($directInviterReward, $indirectInviterReward, $levelGradeDifference, $orderAmount, $commodityActivityStatistics): void
    {
        $levelGradeDifferenceReward = [
            Agent::LEVEL_GROUP_OWNER => [ // 第一层为 当前用户等级
                Agent::LEVEL_GROUP_OWNER => [ // 第二层为 直接邀请人奖励
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [ // 第二层为 间接邀请人奖励
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        // 这里的 from to 是 amount 内 $levelGradeDifference 后的两个 key (级别) 前后顺序, 因为是无规律的所以单独再定义
                        Agent::LEVEL_ELITE => ['amount' => $levelGradeDifference['elite']['group_owner'], 'type' => AgentRevenue::TYPE_COMMISSION, 'from' => 'elite', 'to' => 'group_owner'],
                        Agent::LEVEL_STRONGMAN => ['amount' => $levelGradeDifference['strongman']['group_owner'], 'type' => AgentRevenue::TYPE_COMMISSION, 'from' => 'strongman', 'to' => 'group_owner'],
                    ]
                ],
                Agent::LEVEL_ELITE => [
                    'amount' => $levelGradeDifference['elite']['group_owner'],
                    'type' => AgentRevenue::TYPE_COMMISSION,
                    'from' => 'elite',
                    'to' => 'group_owner',
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $levelGradeDifference['strongman']['elite'], 'type' => AgentRevenue::TYPE_COMMISSION, 'from' => 'strongman', 'to' => 'elite'],
                    ]
                ],
                Agent::LEVEL_STRONGMAN => [
                    'amount' => $levelGradeDifference['strongman']['group_owner'],
                    'type' => AgentRevenue::TYPE_COMMISSION,
                    'from' => 'strongman',
                    'to' => 'group_owner',
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                    ]
                ]
            ],
            Agent::LEVEL_ELITE => [
                Agent::LEVEL_GROUP_OWNER => [
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $levelGradeDifference['strongman']['elite'], 'type' => AgentRevenue::TYPE_COMMISSION, 'from' => 'strongman', 'to' => 'elite'],
                    ]
                ],
                Agent::LEVEL_ELITE => [
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $levelGradeDifference['strongman']['elite'], 'type' => AgentRevenue::TYPE_COMMISSION, 'from' => 'strongman', 'to' => 'elite'],
                    ]
                ],
                Agent::LEVEL_STRONGMAN => [
                    'amount' => $levelGradeDifference['strongman']['elite'],
                    'type' => AgentRevenue::TYPE_COMMISSION,
                    'from' => 'strongman',
                    'to' => 'elite',
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                    ]
                ]
            ],
            Agent::LEVEL_STRONGMAN => [
                Agent::LEVEL_GROUP_OWNER => [
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                    ]
                ],
                Agent::LEVEL_ELITE => [
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                    ]
                ],
                Agent::LEVEL_STRONGMAN => [
                    'amount' => $directInviterReward,
                    'type' => AgentRevenue::TYPE_DIRECT_INVITATION_REWARD,
                    'indirect' => [
                        Agent::LEVEL_GROUP_OWNER => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_ELITE => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                        Agent::LEVEL_STRONGMAN => ['amount' => $indirectInviterReward, 'type' => AgentRevenue::TYPE_INDIRECT_INVITATION_REWARD],
                    ]
                ]
            ],
        ];
        if ($this->directInviter) {
            $rewardSetting = $levelGradeDifferenceReward[$this->agentSnapshot['level']][$this->directInviterSnapshot['level']]; // 邀请奖励配置
            $rewardAmountDetail = $rewardSetting['amount']; // 邀请奖励具体金额数量
            $this->directInviter->incrementOrDecrementBalance(
                $rewardAmountDetail['total'], // 所有 sku 奖励总和
                $rewardSetting['type'],
                $this->order,
                'increment',
                $this->orderCreatedAt
            );
            // SKU 佣金数量统计
            foreach ($rewardAmountDetail['sku_details'] as $skuId => $skuDetail) {
                if ($rewardSetting['type'] === AgentRevenue::TYPE_COMMISSION) {
                    // [统计] SKU 佣金
                    $this->commodityActivitySkuStatistics[$skuId]
                        ->incrementOrDecrementNumberOfCommissions(
                            $skuDetail['quantity'],
                            $skuDetail['unit_price'],
                            sprintf('number_of_%s_with_%s_commissions', $rewardSetting['from'], $rewardSetting['to']));
                } else {
                    // [统计] SKU 邀请奖励
                    $this->commodityActivitySkuStatistics[$skuId]->incrementOrDecrementNumberOfInvitationRewards($skuDetail['quantity'], $skuDetail['unit_price']);
                }
            }
            // 团队业绩
            $this->directInviter->incrementOrDecrementTeamPerformance($orderAmount, 'increment', $this->orderCreatedAt);
            // 团队收入
            $this->directInviter->incrementOrDecrementTeamIncome($this->order['income'], 'increment', $this->orderCreatedAt);
            // 培养奖另算
            $cultivationAward = 0;
            if ($this->agentSnapshot['cultivation_award'] === Agent::CULTIVATION_AWARD_OPEN
                && $this->agentSnapshot['level'] === Agent::LEVEL_STRONGMAN
                && $this->directInviterSnapshot['level'] === Agent::LEVEL_STRONGMAN) {

                $cultivationAward = Agent::CULTIVATION_AWARD;
                $this->directInviter->incrementOrDecrementBalance(
                    $cultivationAward,
                    AgentRevenue::TYPE_CULTIVATE_REWARDS,
                    $this->order,
                    'increment',
                    $this->orderCreatedAt
                );
                // 培养奖统计
                $commodityActivityStatistics->incrementOrDecrementCultivationAwards();
            }

            // 团队订单关联
            $commission = 0;
            $reward = 0;
            // 佣金还是奖励
            if ($rewardSetting['type'] === AgentRevenue::TYPE_COMMISSION) {
                $commission = $rewardAmountDetail['total'];
            } else {
                $reward = $rewardAmountDetail['total'];
            }
            $this->directInviter->relatedOrders()->attach([$this->order['id'] => [
                'type' => Agent::AGENT_ORDER_IDENTITY_TEAM,
                'reward_summary' => $reward, // 奖励
                'commission_summary' => $commission, // 佣金
                'cultivation_awards_summary' => $cultivationAward, // 培养奖
            ]]);
        }

        if ($this->indirectInviter) {
            $rewardSetting = $levelGradeDifferenceReward[$this->agentSnapshot['level']][$this->directInviterSnapshot['level']]['indirect'][$this->indirectInviterSnapshot['level']]; // 邀请奖励配置
            $rewardAmountDetail = $rewardSetting['amount']; // 邀请奖励具体金额数量
            $this->indirectInviter->incrementOrDecrementBalance(
                $rewardAmountDetail['total'],
                $rewardSetting['type'],
                $this->order,
                'increment',
                $this->orderCreatedAt
            );
            foreach ($rewardAmountDetail['sku_details'] as $skuId => $skuDetail) {
                if ($rewardSetting['type'] === AgentRevenue::TYPE_COMMISSION) {
                    // [统计] SKU 佣金
                    $this->commodityActivitySkuStatistics[$skuId]
                        ->incrementOrDecrementNumberOfCommissions(
                            $skuDetail['quantity'],
                            $skuDetail['unit_price'],
                            sprintf('number_of_%s_with_%s_commissions', $rewardSetting['from'], $rewardSetting['to'])
                        );
                } else {
                    // [统计] SKU 邀请奖励
                    $this->commodityActivitySkuStatistics[$skuId]
                        ->incrementOrDecrementNumberOfInvitationRewards(
                            $skuDetail['quantity'],
                            $skuDetail['unit_price'],
                            'indirect'
                        );
                }
            }
            // 团队业绩
            $this->indirectInviter->incrementOrDecrementTeamPerformance($orderAmount, 'increment', $this->orderCreatedAt);
            // 团队收入
            $this->indirectInviter->incrementOrDecrementTeamIncome($this->order['income'], 'increment', $this->orderCreatedAt);

            // 团队订单关联
            $commission = 0;
            $reward = 0;
            // 佣金还是奖励
            if ($rewardSetting['type'] === AgentRevenue::TYPE_COMMISSION) {
                $commission = $rewardAmountDetail['total'];
            } else {
                $reward = $rewardAmountDetail['total'];
            }
            $this->indirectInviter->relatedOrders()->attach([$this->order['id'] => [
                'type' => Agent::AGENT_ORDER_IDENTITY_TEAM,
                'reward_summary' => $reward, // 奖励
                'commission_summary' => $commission, // 佣金
            ]]);
        }
    }
}
